<?php
include_once 'common/Constant.class.php';
include_once 'controller/AdController.php';

/**
 * Class IndexController
 * m: mainview
 * s: sub main
 * t: tag
 * p: page
 *
 */

class IndexController extends  Controller{


	public function index($param){
		$this->show($param);
	}
	public function show($param){
        $pms = Constant::extendUrls($param[0]);
		$this->getSmarty();
		$_SESSION['mainNavItem']= $pms['m'];
		$_SESSION['subNavItem']= $pms['s'];

		$this->initBasicData();
		$this->loadLanGames($pms);
		$this->smarty->assign ( 'hotgames', $this->loadLanHotGames() );
		$this->smarty->assign ( 'navs', $this->loadLanLeftNavs() );
//		$this->smarty->assign ( 'pagesets', Constant::indexHeader() );
		$this->smarty->assign ( 'friendlinks', $this->loadFriendLinks() );
		$this->smarty->assign ( 'curPageType',"var pagetype=0;");

        $this->smarty->assign ( 'seoMsg',  Constant::getSeoMsg('home'));
		$this->smarty->display("theme/home.tpl");
	}
	public function listTagGames($param){
        $pms = Constant::extendUrls($param[0]);
		$this->getSmarty();
		$this->initBasicData();
		$this->initTagGames($pms);
		$this->smarty->assign ( 'hotgames', $this->loadLanHotGames() );
		$this->smarty->assign ( 'navs', $this->loadLanLeftNavs() );

		require_once SERVICE . DS . "IndexDataService.class.php";
		$common = new IndexDataService ( $this->getDB ());

		$tag = $common->getTagItem($pms['t']);
//		$this->smarty->assign ( 'pagesets', Constant::initTagSeo($tag) );
		$this->smarty->assign ( 'friendlinks', $this->loadFriendLinks() );
		$this->smarty->assign ( 'curPageType',"var pagetype=0;");

        $this->smarty->assign ( 'seoMsg',  Constant::getSeoMsg('tag'));
		$this->smarty->display("theme/home.tpl");
	}
	public function loadGameItem($param){
		$this->getSmarty();
		$this->initBasicData();

        $gameid = Constant::extendSingleGameURLID($param[0]);
		$this->smarty->assign ( 'hotgames', $this->loadLanHotGames() );
		$this->smarty->assign ( 'navs', $this->loadLanLeftNavs() );
		$loadGame = $this->setGame($gameid) ;
		$loadGame->gamtags = $this->setGameTags($gameid);
		$this->smarty->assign ( 'game', $loadGame);
		$this->smarty->assign ( 'gamtags', $this->setGameTags($gameid) );
//		$this->smarty->assign ( 'pagesets', Constant::initGameSeo($loadGame) );
		$this->smarty->assign ( 'friendlinks', $this->loadFriendLinks() );
		$this->smarty->assign ( 'curPageType',"var pagetype=1;");
        $this->smarty->assign ( 'systype', $_SESSION["mainNavItem"]);
		$this->crumbreadlist($loadGame,null);
		//加载统计信息
		$control = new AdController ();
		$control->statistic($loadGame->id, 0);
        $this->smarty->assign ( 'seoMsg',  Constant::getSeoMsg('game'));
		$this->smarty->display("theme/item.tpl");
	}
	public function directItem($param){
		$this->getSmarty();
		$this->initBasicData();
        $gameid = Constant::extendSingleGameURLID($param[0]);
		$this->smarty->assign ( 'hotgames', $this->loadLanHotGames() );
		$this->smarty->assign ( 'navs', $this->loadLanLeftNavs() );
		$loadGame = $this->setGame($gameid) ;
		$loadGame->gamtags = $this->setGameTags($gameid);


        $control = new AdController();
        $code = $control->affcode($loadGame->site,$loadGame->language);
        if($loadGame->downloadurl != null){
            $url = str_replace("{afcode}", $code,$loadGame->downloadurl);
        }else{
            $url = str_replace("{afcode}", $code,$loadGame->buyurl);
        }
		$loadGame->downhref = $url;
        $loadGame->downloadiframe = str_replace("{afcode}", $code,$loadGame->downloadiframe);

        $loadGame->returnhref = WEBSITE_URL."index/loadGameItem/".Constant::createSingleGameURL($loadGame);
        $this->smarty->assign ( 'game', $loadGame);
//		$this->smarty->assign ( 'pagesets', Constant::initGameSeo($loadGame) );
		$this->smarty->assign ( 'friendlinks', $this->loadFriendLinks() );
		$this->smarty->assign ( 'curPageType',"var pagetype=2;");
        $this->smarty->assign ( 'systype', $_SESSION["mainNavItem"]);

        $crumbtext ="";
        if($_SESSION["mainNavItem"] == 'og'){
            $crumbtext = 'play' ;
        }else{
            if($loadGame->downloadurl != null){
                $crumbtext = 'down' ;
            }else{
                $crumbtext = 'buy' ;
            }
        }
		$this->crumbreadlist($loadGame,$crumbtext);
			//加载统计信息
		$control = new AdController ();
		$control->statistic($loadGame->id, 1);
        $this->smarty->assign ( 'seoMsg',  Constant::getSeoMsg('down'));
		$this->smarty->display("theme/down.tpl");
	}


	public function  crumbreadlist($loadGame,$lastname){
		//
 		$strlan = $this->smarty->getTemplateVars('str');
		$crumbreadlist[] = array(
			'href'=>WEBSITE_URL.'index/show/m'.$mainNav = $_SESSION["mainNavItem"]."_s.html",
			'name' =>$strlan['home'],
			'append' =>'>'
		);
        if(!empty($loadGame->genre_name)){
            $crumbreadlist[] = array(
                'href'=>WEBSITE_URL.'index/show/m'.$mainNav = $_SESSION["mainNavItem"]."_s".$loadGame->genre_name.".html",
                'name' =>$loadGame->genre_name,
                'append' =>'>'
            );
        }

        if($lastname == null){
            $crumbreadlist[] = array(
                'name' =>$loadGame->game_name
            );
        }else{
            $crumbreadlist[] = array(
                'href'=>WEBSITE_URL.'index/loadGameItem/'.Constant::createSingleGameURL($loadGame),
                'name' =>$loadGame->game_name,
                'append' =>'>'
            );
            $crumbreadlist[] = array(
 		        'name' =>$lastname
 		    );
        }
		$this->smarty->assign ( 'crumbreadlist',$crumbreadlist);
	}
	
	public function initBasicData(){
		
		$this->smarty->assign("weburl","var weburl='".WEBSITE_URL."';");//网站地址
		//初始化header,语言,一二级导航菜单
		$this->smarty->assign ( 'languages', $this->initLanList());
		$mainNavs = $this->initMainNavs();
		$this->smarty->assign ( 'mainNavs', $mainNavs);
		if($_SESSION['mainNavItem'] == null){
			$_SESSION['mainNavItem'] = $mainNavs[0]['title'];
		}
		include_once 'lang/'.$_SESSION['language'].'.lang.php';
		$this->smarty->assign ( 'str', $str);
		$this->smarty->assign ( 'subNavs', $this->initSubNavs($str));
	}

	public function  setGameTags($gameid){

		require_once SERVICE . DS . "IndexDataService.class.php";
		$common = new IndexDataService ( $this->getDB ());
		$tags = $common->getGameTags($gameid);
		return $tags;
	}
	public function  setGame($gameid){
		require_once SERVICE . DS . "IndexDataService.class.php";
		$common = new IndexDataService ( $this->getDB ());
		$igame = $common->getGameItem($gameid);
		$igame->direct_href = WEBSITE_URL."index/directItem/".Constant::createSingleGameURL($igame);

		if(!empty($igame->img_screen1) ){
			$gameimages[] = array($igame->img_screen1);
		}
		if(!empty($igame->img_screen2) ){
			$gameimages[] = array($igame->img_screen2);
		}
		if(!empty($igame->img_screen3) ){
			$gameimages[] = array($igame->img_screen3);
		}
		$igame->gameimages = $gameimages;
		return $igame;
	}
	//初始化主菜单
	public function  initMainNavs(){
		$canvertDic = array("pc"=>"Pc Games","og"=>"Online Games","mac"=>"Mac Games");
		$cacheln = $_SESSION["language"];
		$mainNav = $_SESSION["mainNavItem"];

		require_once SERVICE . DS . "IndexDataService.class.php";
		$common = new IndexDataService ( $this->getDB ());
		$navs = $common->loadMainNavs();
		if(empty($mainNav)){
			$mainNav=$navs[0]->gametype;
		}
		$datas=array();
		foreach ($navs as $item){
			if($item->gametype == $mainNav){
				$datas[] = array(
				'title'=>$item->gametype,
				'state'=>'selected',
                'gname'=>$item->gametype,
				'name'=>$canvertDic[$item->gametype]
				);
			}else{
				$datas[] = array(
				'title'=>$item->gametype,
				'state'=>'a',
                'gname'=>$item->gametype,
				'name'=>$canvertDic[$item->gametype]
				);
			}
		}
		return $datas;
	}
	//初始化主菜单下二级菜单
	public function  initSubNavs($str){
		$cacheln = $_SESSION["language"];
		require_once SERVICE . DS . "IndexDataService.class.php";
		$common = new IndexDataService ( $this->getDB ());
		$mainNavs = $this->initMainNavs();



		$datas=array();
		foreach ($mainNavs as $item){
			if($item['state'] == "a"){
				$state = "hidden";
			}else{
				$state = "active";
			}

			$subnavs = $common->loadSubMainItem($item['title'],$cacheln);
			if($subnavs != null){
                if( $_SESSION['mainNavItem'] ==$item['title'] &&  $_SESSION['subNavItem'] == null){
                    $subnavs[0] = array(
                        'genre_name'=>$str['0'],
                        'href' =>WEBSITE_URL."index/show/m".$item['title']."_s.html",
                        'state'=>'active'
                    );
                }else{
                    $subnavs[0] = array(
                        'genre_name'=>$str['0'],
                        'href' =>WEBSITE_URL."index/show/m".$item['title']."_s.html"
                    );
                }

			}
			$datas[] = array(
				'id'=>$item['title'],
				'state'=>$state,
				'values'=>$subnavs
			);
		}
		return $datas;
	}

	//修改系统语言版本后切换显示
	public function changeLan(){
		if(!empty($_POST['ln'])){
			setcookie('gamesitebuilderlanguage',$_POST['ln'],time()+60*60*24*30,"/");
		};
		echo WEBSITE_URL."index/show";
	}
	//初始化语言信息列表
	public function initLanList(){
		require_once SERVICE . DS . "IndexDataService.class.php";
		include_once 'lang/admin/country.lang.php';
		$common = new IndexDataService ( $this->getDB ());
		$cacheln = $_COOKIE["gamesitebuilderlanguage"];
		if(empty($cacheln)){
			$cacheln =  $common->getDefaultLan();
			setcookie('gamesitebuilderlanguage',$cacheln,time()+60*60*24*30,"/");
		}
		$_SESSION['language'] = $cacheln;
		$datas=array();
		$language = $common->getGameLans();
		$contain = false;
		foreach ($language as $value){
			if($value->language == $cacheln){
				$lreults=array(
					'lan'=>$value->language,
					'select'=>"selected",
					'name'=>$lnstr[$value->language]
					);
					$contain = true;
			}else {
				$lreults=array(
					'lan'=>$value->language,
					'name'=>$lnstr[$value->language]
				);
			}
			$datas[] = $lreults;
		}
		if(!$contain){
			$cacheln=$language[0]->language;
			$_SESSION['gamesitebuilderlanguage'] = $cacheln;
			setcookie('gamesitebuilderlanguage',$cacheln,time()+60*60*24*30,"/");
		}
		return $datas;
	}

	//加载语言类游戏列表
	public function loadLanGames($pms){
		//		$this->getSmarty();
		$ln = $_SESSION['language'];
		$mainNav = $_SESSION["mainNavItem"];
		$subMainNav = $_SESSION['subNavItem'];
        $oms = array();
		if(!empty($ln)){
			$query .= " and language='".$ln."'";
		}
		if(!empty($mainNav)){
			$query .= " and gametype='".$mainNav."'";
            $oms[] ="m".$mainNav;
		}
		if(!empty($subMainNav)){
			$query .= " and genre_name='".$subMainNav."'";
            $oms[] ="s".$subMainNav;
		}
		require_once SERVICE . DS . "IndexDataService.class.php";
		$common = new IndexDataService ( $this->getDB ());
		$page = $pms['p'] == null? 1:$pms['p'];
		$index = ($page-1) * 56;
		$game = $common->loadLanGames($index,56,$query);
		$results = array();
		foreach($game as $gitem){
			$results[]=array(
				'href'=>WEBSITE_URL."index/loadGameItem/".Constant::createSingleGameURL($gitem),
				'game_name'=>$gitem->game_name,
				'img'=>$gitem->img
			);
		}
		$this->smarty->assign ( 'games', $results );
		$totalCount = $common->countNum($query);
		$pagenum = ceil($totalCount/56);
        $this->smarty->assign ( 'pageurl', WEBSITE_URL."index/show/".implode("_",$oms)."_p");
	//	$this->smarty->assign ( 'pageurl', "var pageurl = '".WEBSITE_URL."index/show/r=1".$kestr."&page='" );
		$this->smarty->assign ( 'totalpage', $pagenum );
 		$this->smarty->assign ( 'curpage', $page );
	}

	

	public function initTagGames($pms){
		//		$this->getSmarty();
		$ln = $_SESSION['language'];
        $oms = array();
		$mainNav = $_SESSION["mainNavItem"];

		if(!empty($ln)){
			$query .= " and language='".$ln."'";
		}
		if(!empty($mainNav)){
			$query .= " and gametype='".$mainNav."'";
            $oms[] ="m".$mainNav;

		}

		$query.= " and tag_id = ".$pms['t'];
        $oms[]="t".$pms['t'];
			
		require_once SERVICE . DS . "IndexDataService.class.php";

        $common = new IndexDataService ( $this->getDB ());
        $page = $pms['p'] == null? 1:$pms['p'];
        $index = ($page-1) * 56;
        $game = $common->loadTagGames($index,56,$query);
        $results = array();
        foreach($game as $gitem){
            $results[]=array(
				'href'=>WEBSITE_URL."index/loadGameItem/".Constant::createSingleGameURL($gitem),
                'game_name'=>$gitem->game_name,
                'img'=>$gitem->img
            );
        }
        $this->smarty->assign ( 'games', $results );
        $totalCount = $common->countTagGames($query);

        $pagenum = ceil($totalCount/56);
        $this->smarty->assign ( 'pageurl', WEBSITE_URL."index/listTagGames/".implode("_",$oms)."_p");
     //   $this->smarty->assign ( 'pageurl', "var pageurl = '".WEBSITE_URL."index/listTagGames/r=1".$kestr."&page='");
        $this->smarty->assign ( 'totalpage', $pagenum );
        $this->smarty->assign ( 'curpage', $page);
	}

	//加载语言热门类游戏列表
	public function loadLanHotGames(){
		$ln = $_SESSION['language'];
		$mainNav = $_SESSION["mainNavItem"];
		$subMainNav = $_SESSION['subNavItem'];
		$query;
		if(!empty($ln)){
			$query .= " and language='".$ln."'";
		}
		if(!empty($mainNav)){
			$query .= " and gametype='".$mainNav."'";
		}
		require_once SERVICE . DS . "IndexDataService.class.php";
		$common = new IndexDataService ( $this->getDB ());
		$game = $common->loadLanHotGames($query);
		$results = array();
		foreach($game as $gitem){
			$results[]=array(
				'href'=>WEBSITE_URL."index/loadGameItem/".Constant::createSingleGameURL($gitem),
				'game_name'=>$gitem->game_name,
				'img'=>$gitem->img
			);
		}
		return $results;
	}
	//加载语言热门类游戏列表
	public function loadLanLeftNavs(){
		require_once SERVICE . DS . "IndexDataService.class.php";
		$common = new IndexDataService ( $this->getDB ());
		$navs = $common->getHotTags();
		return $navs;
	}
	public function loadFriendLinks(){
		require_once SERVICE . DS . "IndexDataService.class.php";
		$common = new IndexDataService ( $this->getDB ());
		$links = $common->getFriendLinks();
		return $links;
	}

}